package com.nmgsr.ptmsapp.utils;

import cn.hutool.core.util.HexUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.SM2;
import org.bouncycastle.crypto.engines.SM2Engine;

public class SM2Util {

    // 公钥与私钥（HEX格式）
    public static final String SM2_PUBLIC_KEY = "04391AD6FCCB674065F4F38DF5F458C540FA947B94E35F9717BB3032601B5DA876AEAAAFCC79AFEE6DDAA81F7D6E71FC568E6FE5B3F85179213F7F0283B4F5A572";
    public static final String SM2_PRIVATE_KEY = "072D52487322124452F689BF2912DCCE42FAB73F5AEEF532B7A30E8D109C9320";

    // 正确初始化模式（直接传递SM2Engine.Mode枚举）
    private static final SM2 sm2 = new SM2(
            HexUtil.decodeHex(SM2_PRIVATE_KEY),
            HexUtil.decodeHex(SM2_PUBLIC_KEY)
    );
    static {
        sm2.setMode(SM2Engine.Mode.C1C3C2);  // 使用Hutool原生方法设置加密模式
    }

    /**
     * 加密为C1C3C2格式HEX字符串
     */
    public static String encryptToC1C3C2Hex(String data) {
        return sm2.encryptHex(data, KeyType.PublicKey);
    }

    /**
     * 解密C1C3C2格式HEX密文
     */
    public static String decryptFromC1C3C2Hex(String cipherHex) {
        return sm2.decryptStr(cipherHex, KeyType.PrivateKey);
    }

    // 密钥验证（应用启动时调用）
    public static void validateKeys() {
        validatePublicKey(SM2_PUBLIC_KEY);
        validatePrivateKey(SM2_PRIVATE_KEY);
    }

    private static void validatePublicKey(String pubKeyHex) {
        if (!pubKeyHex.startsWith("04") || pubKeyHex.length() != 130) {
            throw new IllegalArgumentException("公钥必须以04开头且长度为130字符");
        }
        // 验证坐标值是否在曲线域内
        try {
            new SM2(null, pubKeyHex).getPublicKey();
        } catch (Exception e) {
            throw new IllegalArgumentException("公钥坐标值无效", e);
        }
    }

    private static void validatePrivateKey(String priKeyHex) {
        if (priKeyHex.length() != 64) {
            throw new IllegalArgumentException("私钥必须为64字符HEX字符串");
        }
    }
}
